<template>
    <div>
        <el-dialog v-model="props.AssembleVisible" :title="newTitle" draggable width="500px"
            @close="handleAssembleClose">
            <el-form :inline="true" :model="props.listItem" label-width="auto" label-position="left"
                v-if="newTitle == '查看密码'">
                <el-form-item label="账号" prop="username">
                    <el-space spacer=" ">
                        <el-input v-model.trim="props.listItem.username" placeholder="请输入" disabled
                            style="width: 300px" />
                        <el-button type="primary" :icon="Document" circle link v-copyText="props.listItem.username"
                            v-copyText:callback="copyTextSuccess" />
                    </el-space>
                </el-form-item>
                <el-form-item label="密码/密钥" prop="password">
                    <el-space spacer=" ">
                        <el-input v-model.trim="props.listItem.password" placeholder="请输入" disabled style="width: 300px"
                            :type="showType" />
                        <el-button type="primary" :icon="View" circle link @click="handleCopy(1)" />
                        <el-button type="primary" :icon="Document" circle link v-copyText="props.listItem.password"
                            v-copyText:callback="copyTextSuccess" />
                    </el-space>
                </el-form-item>
            </el-form>
            <el-form :inline="true" :model="accountFrom" label-width="auto" label-position="left"
                v-if="newTitle == '修改密码' && props.typeAssemble === 2">
                <el-form-item label="新密码" prop="password" style="width: 100%">
                    <el-input v-model.trim="accountFrom.password" placeholder="请输入" type="password" show-password />
                </el-form-item>
            </el-form>


            <el-form :inline="true" :model="submitFrom" label-width="auto" label-position="left"
                v-if="newTitle == '修改密码' && props.typeAssemble === 1" :rules="rules" ref="checkServerRef">
                <el-form-item label="密码类型" style="width: 100%" prop="pwdType" required>
                    <el-radio-group v-model="submitFrom.pwdType" @change="changePwd">
                        <el-radio value="pwd">密码</el-radio>
                        <el-radio value="secretKey">密钥</el-radio>
                    </el-radio-group>
                </el-form-item>



                <el-form-item label="新密码" prop="serverPassword" style="width: 100%" v-if="submitFrom.pwdType == 'pwd'"
                    :required="submitFrom.pwdType == 'pwd'">
                    <el-input v-model.trim="submitFrom.serverPassword" placeholder="请输入" type="password"
                        show-password />
                </el-form-item>
                <el-form-item label="新密钥" prop="serverSecretKey" style="width: 100%"
                    v-if="submitFrom.pwdType == 'secretKey'" :required="submitFrom.pwdType == 'secretKey'">
                    <el-input v-model.trim="submitFrom.serverSecretKey" placeholder="请输入" show-password type="textarea"
                        :autosize="{ minRows: 5 }" />
                </el-form-item>
                <el-form-item label="加载密钥" v-if="submitFrom.pwdType == 'secretKey'">
                    <el-upload class="upload-demo" drag action="#" multiple :before-upload="handleBeforeUpload"
                        :limit="1" :on-exceed="handleExceed" style="width: 430px">
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <template #tip>
                            <div class="el-upload__tip">只能上传{{ sys_fileType.join("/") }} 文件</div>
                        </template>
                    </el-upload>
                </el-form-item>


            </el-form>



            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleAssembleSure">
                        修改密码
                    </el-button>
                    <el-button @click="handleAssembleClose">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch, reactive } from "vue";
import {
    Document, View
} from '@element-plus/icons-vue'
const emits = defineEmits(["handleAssembleClose", "handleAssembleSure"]);
const { proxy } = getCurrentInstance();
const props = defineProps({
    AssembleVisible: {
        type: Boolean,
        default: false,
    },
    // 传值数据对象
    listItem: {
        type: Object,
        default: {},
    },
    typeAssemble: {
        type: Number,
        default: 1//1是可以选择密码和密钥2不可以被选择
    }
});
const newTitle = ref('')
const showType = ref('password')
const accountFrom = ref({
    providerId: null,
    username: '',
    registerTime: '',
    updatePassword: true,
    pwdType: 'pwd',
    password: '',
    oldPassword: ''
})
const submitFrom = ref({
    serverNo: "", //服务器编号
    cloudServerProviderId: null, //服务商
    cloudServerId: null, //服务商账号
    countryId: null, //国家
    countryZoneId: null, //地区
    pwdType: "", //密码类型
    serverAccount: '',//用户名
    serverPassword: null,//密码
    serverSecretKey: null,//密钥
    startTime: null, //开始时间
    expireTime: null, //到期时间
    status: null, //状态
    updatePassword: true,
    oldPassword: ''
}); //参数
const sys_fileType = reactive(['txt', "text", "key", "pem"])

watch(
    () => props.AssembleVisible,
    () => {
        if (!props.AssembleVisible) return;
        handleProcessing()//处理逻辑
    })
const handleAssembleSure = () => {
    if (newTitle.value == '查看密码') {
        newTitle.value = '修改密码'

    } else {
        if (props.typeAssemble === 1) {
            proxy.$refs["checkServerRef"].validate((valid) => {
                if (!valid) return
                site.general
                    .siteserverUpdatebyid({
                        pathParams: {
                            id: props.listItem.id,
                        },
                        data: submitFrom.value
                    })
                    .then((res) => {
                        if (res.code === 200) {
                            proxy.$modal.msgSuccess("修改成功");
                            handleEmpty()
                            emits("handleAssembleSure");
                        }
                    })
            })
        } else {
            if (!accountFrom.value.password) return proxy.$modal.msgError('请输入密码')
            site.general
                .sitecloudserverUpdatebyid({
                    pathParams: { id: props.listItem.id },
                    data: accountFrom.value
                })
                .then((res) => {
                    if (res.code === 200) {
                        proxy.$modal.msgSuccess("修改成功");
                        emits("handleAssembleSure");
                    }
                });
        }
    }
}
const handleAssembleClose = () => {// 取消事件
    if (newTitle.value == '查看密码') {
        emits('handleAssembleClose')
        handleEmpty()
    } else {
        newTitle.value = '查看密码'
    }
};
const handleCopy = (index) => {
    if (index == 1) {//查看密码
        if (showType.value == 'password') {
            showType.value = 'text'
        } else {
            showType.value = 'password'
        }
    }
}
/** 复制代码成功 */
function copyTextSuccess() {
    proxy.$modal.msgSuccess("复制成功");
}
const handleProcessing = () => {
    newTitle.value = '查看密码'
    if (props.typeAssemble === 1) {
        site.general
            .siteserverGetbyid({
                pathParams: {
                    id: props.listItem.id,
                },
            })
            .then((res) => {
                console.log(res.data);
                submitFrom.value.serverNo = res.data.serverNo;
                submitFrom.value.cloudServerProviderId = res.data.cloudServerProviderId;
                submitFrom.value.cloudServerId = res.data.cloudServerId;
                submitFrom.value.countryId = res.data.countryId;
                submitFrom.value.countryZoneId = res.data.countryZoneId;
                submitFrom.value.serverAccount = res.data.serverAccount;
                submitFrom.value.pwdType = props.listItem.pwdType;
                submitFrom.value.oldPassword = props.listItem.password
                submitFrom.value.startTime = res.data.startTime;
                submitFrom.value.expireTime = res.data.expireTime;
                submitFrom.value.status = res.data.status;
            })
    } else {
        accountFrom.value.providerId = props.listItem.providerId
        accountFrom.value.username = props.listItem.username
        accountFrom.value.registerTime = props.listItem.lastModified
        accountFrom.value.updatePassword = true
        accountFrom.value.oldPassword = props.listItem.password
    }
}
const rules = reactive({
    serverPassword: [{ required: true, message: "请输入", trigger: "blur" }],
    serverSecretKey: [{ required: true, message: "请输入", trigger: "blur" }],

});
const handleBeforeUpload = (file) => {
    if (handelFileType(file.name)) return proxy.$modal.msgWarning(`文件格式不正确, 请上传${fileType.join("/")}文件!`);
    const isLt = file.size / 1024 / 1024 < 1;
    if (!isLt) return proxy.$modal.msgWarning(`文件大小不能超过1MB}文件!`);
    const fileReader = new FileReader();
    fileReader.onload = (e) => {
        submitFrom.value.serverSecretKey = e.target.result
    }
    fileReader.onerror = () => {
        proxy.$modal.msgWarning(`上传失败，请检查文件类型`);
    };
    fileReader.onerror = (err) => {
        proxy.$modal.msgWarning(`文件读取失败：${err}`);
    };
    fileReader.readAsText(file); // 使用 ArrayBuffer 处理二进制数据
}
// 文件个数超出
const handleExceed = () => {
    proxy.$modal.msgError(`上传文件数量不能超过 1 个!`);
}
const handelFileType = (name) => {
    return !sys_fileType.includes(name.split('.')[1].toLowerCase()) ? true : false;
}
const changePwd = (e) => {
    if (e === 'pwd') {
        submitFrom.value.serverSecretKey = null
    } else {
        submitFrom.value.serverPassword = null
    }
}
const handleEmpty = () => {
    proxy.resetForm("checkServerRef");

    showType.value = 'password'
    accountFrom.value.providerId = null
    accountFrom.value.username = ''
    accountFrom.value.registerTime = ''
    accountFrom.value.updatePassword = true
    accountFrom.value.pwdType = 'pwd'
    accountFrom.value.password = ''
    accountFrom.value.oldPassword = ''

    submitFrom.value.serverNo = '';
    submitFrom.value.cloudServerProviderId = null;
    submitFrom.value.cloudServerId = null;
    submitFrom.value.countryId = null;
    submitFrom.value.countryZoneId = null;
    submitFrom.value.serverAccount = '';
    submitFrom.value.pwdType = '';
    submitFrom.value.oldPassword = ''
    submitFrom.value.startTime = '';
    submitFrom.value.expireTime = '';
    submitFrom.value.status = null;

}
</script>